package com.guessdroid.UI;

import com.guessdroid.R;
import com.guessdroid.labeling.*;
import com.guessdroid.sensing.*;
import com.guessdroid.util.*;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;

public class GuessActivity extends Activity {

	private GContext guessResult = null;
	GContextList list = null;
	private Keeper details;
	private Measurement measurement;
	private DataPoints oldData;
	private Handler handler;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());
		setContentView(R.layout.activity_guess);
		setButtonClickListeners();
		list = getGContextList();
		details = new Keeper(this, getApplication());
		measurement = new Measurement(details);
		details.mWakeLock.acquire();
		measurement.start();
		handler = new Handler();
		handler.postDelayed(new Runnable() {
			public void run() {
				doGuessing();
			}
		}, Constants.GUESS_SAMPLE_LENGTH);
		loadOldData();
	}

	private void loadOldData() {
		oldData = (DataPoints) AndroidWriter
				.readObjectFromFile(Constants.DATAPOINTS_FILE); // contains all knowledge up to now
	}

	private void doGuessing() {
		RawData newData = measurement.stopAndGetData();
		if (oldData != null) {
			showResult(Guess(newData));
		} else {
			showResult("Unknown");
		}
	}

	private void setButtonClickListeners() {
		Button correct = (Button) findViewById(R.id.correctButton);
		correct.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				handleResultAndGotoHome(true);
			}
		});
		Button wrong = (Button) findViewById(R.id.wrongButton);
		wrong.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				handleResultAndGotoHome(false);
			}
		});
	}
	
	private void handleResultAndGotoHome(boolean isCorrect) {
		if (guessResult != null) {
			list.saveGuessResult(guessResult.id, isCorrect);
			handleCollectedDataPoints(isCorrect);
		}
		Intent intent = new Intent(GuessActivity.this, HomeActivity.class);
		startActivity(intent);
	}

	private GContextList getGContextList() {
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			return (GContextList) extras.get("contexts");
		}
		return null;
	}

	private String Guess(RawData new_data) {
		try {
			new_data.preProcess(); // eliminate garbage data from the beginning
		} catch (Exception e) {
			return "UnKnown";
		}

		DataPoints processed = new DataPoints(new_data, Constants.DATAPOINT_INTERVAL);
		if (oldData != null) {
			oldData.merge(processed);
		} else {
			return "UnKnown";
		}
		int guess;
		try {
			guess = oldData.guess();
		} catch (Exception e) {
			return "Unknown";
		} // guesses the label of ALL unguessed points
		guessResult = list.findContextById(guess);
		return guessResult.label;
	}

	private void handleCollectedDataPoints(boolean correct) {
		if (correct) {
			oldData.setGuessResult(guessResult.id);
		} else // obligatory, otherwise pollutes next guess
		{
			oldData.setGuessResult(0);
		}
		AndroidWriter.writeObjectToFile(oldData, Constants.DATAPOINTS_FILE);
	}

	private void showResult(String result) {
		TextView context = (TextView) findViewById(R.id.guessedContext);
		context.setVisibility(View.VISIBLE);
		context.setText(result);

		ProgressBar progress = (ProgressBar) findViewById(R.id.progressBar);
		progress.setVisibility(View.GONE);
		TextView guessing = (TextView) findViewById(R.id.guessingLabel);
		guessing.setVisibility(View.GONE);
	}

}
